package com.chatim.nonamechatim.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chatim.nonamechatim.mapper.MessageMapper;
import com.chatim.nonamechatim.mapper.UserMapper;
import com.chatim.nonamechatim.pojo.Message;
import com.chatim.nonamechatim.service.MessageService;
import com.chatim.nonamechatim.vo.UserListVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserMapper userMapper;

    /**
     * 添加会话列表
     */
    @Override
    public void addContact(Long fid, Long tid) {
        addContacts(fid, tid);
        addContacts(tid, fid);
    }

    /**
     * 查询会话列表
     */
    @Override
    public List<UserListVo> selectContact(Long uid) {
        // 获取会话列表所有id
        String key = "contact:" + uid.toString();
        Set<String> set = stringRedisTemplate.opsForSet().members(key);
        if(set != null && !set.isEmpty()){
            // 获取所有的用户id
            List<Long> list = set.stream().map(Long::parseLong).collect(Collectors.toList());
            // 获取用户信息
            return userMapper.selectBatchIds(list).stream().map(user->{
                UserListVo userListVo = new UserListVo();
                BeanUtils.copyProperties(user, userListVo);
                return userListVo;
            }).toList();
        } else {
            return new ArrayList<>();
        }
    }

    public void addContacts(Long fid, Long tid){
        String key = "contact:" + fid;
        // 判断会话是否存在
        Boolean isExist = stringRedisTemplate.opsForSet().isMember(key, tid.toString());
        if(Boolean.FALSE.equals(isExist)){
            // 如果会话不存在，则添加这个id进会话
            stringRedisTemplate.opsForSet().add(key, tid.toString());
        }
    }
}
